/*
 * This file is part of Sparwe.
 *
 *  Sparwe is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Sparwe is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Sparwe.  If not, see <http://www.gnu.org/licenses/>.
 */ 

#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <iostream>
#include <fstream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/regex.hpp>

#include "exceptions.h"
#include "configreader.h"

using namespace sp_core;

ConfigReader::ConfigReader(std::string filename, std::string sep) : mFilename(filename), mSeparators(sep)
{ReadFile();}

ConfigReader::~ConfigReader()
{

}

bool ConfigReader::VerifyConfig() const
{
	const boost::regex e("([a-z]+[[:space:]]=[[:space:]][0-9]+;)*");
	
	return boost::regex_match(mData, e);
}



std::string ConfigReader::GetSeparators() const
{
	return mSeparators;
}

bool ConfigReader::ReadFile()
{
	typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
	
	std::ifstream inStream(mFilename.c_str());

	if (!inStream.is_open())
		throw new IOException("File not open.");

	std::string tempLine;
	while (!inStream.eof())
	{
		std::getline(inStream, tempLine);
		mData.append(tempLine);
	}

	boost::char_separator<char> sep(mSeparators.c_str());
	tokenizer tokens(mData, sep);

	for (tokenizer::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
	{
		std::string first = *iter;
		std::string second = *(++iter);

		boost::erase_all(first, " ");
		boost::erase_all(second, " ");

		mTokens[first] = second;
	}

	return true;
}
